package pers.ht.mbpo.util;

import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class UploadUtil {

    //读取资源属性文件（properties）
    private static ResourceBundle rb = ResourceBundle.getBundle("pers.ht.mbpo.util.DB-config", Locale.US);

    public static JSONArray getJson() {
        String str = "[{\"code\": 0,\"msg\": \"\",\"data\": {\"src\": \"\"}}]";
        return JSONArray.fromObject(str);
    }

    public static String saveFile(HttpServletRequest request) {
        String SAVE_PATH = rb.getString("savePath");
        File file = new File(SAVE_PATH);
        String filePath = "";
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        try {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            fileUpload.setHeaderEncoding("UTF-8");
            if (!fileUpload.isMultipartContent(request)) {
            }
            List<FileItem> list = fileUpload.parseRequest(request);
            for (FileItem item : list) {
                String fileName = item.getName();

                if (fileName == null || fileName.trim().equals("")) {
                    continue;
                }
                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                InputStream is = item.getInputStream();
                FileOutputStream fos = new FileOutputStream(SAVE_PATH + File.separator + fileName);
                byte buffer[] = new byte[1024];
                int length = 0;
                while ((length = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
                is.close();
                fos.close();
                item.delete();
                filePath = SAVE_PATH + File.separator + fileName;
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
